package com.eureka.eurekaserviceinvoker.controller;

import com.eureka.eurekaserviceinvoker.entity.Person;
import com.eureka.eurekaserviceinvoker.service.CollapserService;
import com.eureka.eurekaserviceinvoker.service.PersonDefaultService;
import com.eureka.eurekaserviceinvoker.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.stream.IntStream;

/**
 *
 * Created by earl on 2018/4/17.
 */
@Configuration
@RestController
@RequestMapping("/invoker")
public class InvokerController {

    @Autowired
    private PersonService personService;


    @Autowired
    private PersonDefaultService  personDefaultService;

    @Autowired
    private CollapserService collapserService;


    //测试@HystrixCommand
    @GetMapping("/person/{id}")
    public Person person(@PathVariable Long id ){
        Person p = personService.getPerson(id);
        return p;
    }

    //测试@DefaultProperties
    @GetMapping("/personDefault/{id}")
    public Person personDefault(@PathVariable Long id ){
        Person p = personDefaultService.getDefaultPerson(id);
        return p;
    }

    //测试缓存注解
    @GetMapping("/personCache/{id}")
    public Person personCache(@PathVariable Long id ){
        Person p = personDefaultService.getCachePerson(id);
        IntStream.range(0,3).forEach(i-> personDefaultService.getCachePerson(id));
        return p;
    }


    //测试合并请求
    @PostMapping("/personBatch")
    public List< Person> personBatch(@RequestBody Long [] ids ) throws ExecutionException, InterruptedException {
        List< Person> list = new ArrayList<>(ids.length);
        // 连续执行3次请求
        Future<Person> f1 = collapserService.getSinglePerson(ids[0]);
        Future<Person> f2 = collapserService.getSinglePerson(ids[1]);
        Future<Person> f3 = collapserService.getSinglePerson(ids[2]);
        Person p1 = f1.get();
        Person p2 = f2.get();
        Person p3 = f3.get();
        System.out.println(p1.getId() + "---" + p1.getName());
        System.out.println(p2.getId() + "---" + p2.getName());
        System.out.println(p3.getId() + "---" + p3.getName());
        list.add(p1);
        list.add(p2);
        list.add(p3);
        return list;
    }


}
